package com.qf.service.impl;

import com.qf.constant.CacheConstants;
import com.qf.model.StandardSubmit;
import com.qf.service.Strategy;
import com.qf.service.api.CacheService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;

import java.io.IOException;
import java.io.StringReader;

/**
 * 敏感词策略
 *
 * @author 何星宇
 * @version V1.0
 * @Date 2021/11/23 19:30
 */

@Service(value = "dirtyWords")
@Slf4j
public class DirtyWordStrategy implements Strategy {
    @Autowired
    private CacheService cacheService;

    @Override
    public boolean strategy(StandardSubmit standardSubmit) throws IOException {
        //记录日志
        log.info("【策略模块-敏感词策略】 敏感词策略开始执行！");
        StringReader stringReader = new StringReader(standardSubmit.getMessageContent());
        //IK分词器
        IKSegmenter ikSegmenter = new IKSegmenter(stringReader, true);
        Lexeme str = null;
        while (true) {
            if ((str = ikSegmenter.next()) == null) {
                break;
            }
            String text = str.getLexemeText();
            //查询redis敏感词判断
            String dirtyWords = cacheService.get(CacheConstants.CACHE_PREFIX_DIRTY_WORDS + text);
            if (!StringUtils.isEmpty(dirtyWords)) {
                //存在敏感词
                log.info("【策略模块-敏感词策略】 短信内容存在敏感词！！ 敏感词：{} 短信内容：{}", text, standardSubmit.getMessageContent());
                return false;
            }
        }
        return true;
    }
}
